﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WaterKit.TcpUdp;
using System.Threading;
using System.Diagnostics;
using System.Windows.Threading;
using System.Data;
using WaterKit.Base;

namespace Auction_Client
{
    /// <summary>
    /// 客户端主程序
    /// </summary>
    public partial class AppWindow : Window
    {
        /// <summary>
        /// 标的开始倒计时定时器
        /// </summary>
        DispatcherTimer startTargetTimer = new DispatcherTimer();
        /// <summary>
        /// 标的结束倒计时定时器
        /// </summary>
        DispatcherTimer endTargetTimer = new DispatcherTimer();
        /// <summary>
        /// 确认标的底价倒计时定时器
        /// </summary>
        DispatcherTimer confirmTimer = new DispatcherTimer();



        /// <summary>
        /// 定时器使用时间
        /// </summary>
        DateTime eventTime = new DateTime();

        /// <summary>
        /// 本地出价记录
        /// </summary>
        DataTable bidPriceDT = new DataTable();

        /// <summary>
        /// 竞价序号
        /// </summary>
        int bidCount = 0;

        /// <summary>
        /// 构造函数
        /// </summary>
        public AppWindow()
        {
            App.connectServer();

            App.client.ReceivedDatagram += new NetEvent(RecvData);
            App.client.DisConnectedServer += new NetEvent(DisConnected);

            //判断登录
            LoginWindow login = new LoginWindow();
            if (login.ShowDialog() == true)
            {
                //构建页面
                InitializeComponent();

                startTargetTimer.Tick += new EventHandler(startTargetTimer_Tick);
                startTargetTimer.Interval = new TimeSpan(0, 0, 1);

                endTargetTimer.Tick += new EventHandler(endTargetTimer_Tick);
                endTargetTimer.Interval = new TimeSpan(0, 0, 1);

                confirmTimer.Tick += new EventHandler(confirmTimer_Tick);
                confirmTimer.Interval = new TimeSpan(0, 0, 1);

                //标的信息
                targetInfo_Init();

                this.Show();
            }
            else
            {
                //关闭程序
                Application.Current.Shutdown();
            }
        }

        /// <summary>
        /// 标的信息
        /// </summary>
        void targetInfo_Init()
        {
            //初始化竞价DataTable
            bidPriceDT.Columns.Add("bidIndex", typeof(int));
            bidPriceDT.Columns.Add("bidTime", typeof(string));
            bidPriceDT.Columns.Add("maxMoney", typeof(string));
            bidPriceDT.Columns.Add("Status", typeof(string));

            //解析标的信息
            string[] targetArr = App.targetStr.Split('|');

            //全局信息
            App.maxMoney = double.Parse(targetArr[3]);
            App.auctionType = targetArr[9].ToString();
            App.auctionTime = Convert.ToInt32(targetArr[10]);
            App.incrementMoney = double.Parse(targetArr[11].ToString());
            App.BidUser = targetArr[13];

            //页面信息
            lblProductName.Content = targetArr[0];
            lblProductPrice.Content = App.maxMoney.ToString("#,###") + "元";
            lblProductNum.Content = targetArr[4];
            lblTargetName.Content = targetArr[5];
            lblAuctioneer.Content = targetArr[8];
            lblAuctionType.Content = App.auctionType == "AUCTION_TYPE02" ? "延时拍卖" : "限时拍卖";
            lblIncrease.Content = App.incrementMoney.ToString("#,###") + "元";
            lblCompanyName.Content = targetArr[14];
            lblSeatmun.Content = targetArr[15];
            lblAuctionUsername.Content = targetArr[16];

            //商品图片
            System.Windows.Media.Imaging.BitmapImage image_uri = new System.Windows.Media.Imaging.BitmapImage();
            image_uri.BeginInit();
            image_uri.UriSource = new Uri(targetArr[2], UriKind.RelativeOrAbsolute);
            image_uri.EndInit();
            imgProductPic.Source = image_uri;

            //同步时限
            Thread.Sleep(1000 - DateTime.Now.Millisecond);
            eventTime = Convert.ToDateTime((targetArr[6]));

            //开始定时器
            startTargetTimer.Start();

            boxStartTarget.Visibility = Visibility.Visible;

            setMaxMoney(true);
        }

        /// <summary>
        /// 更新最高价
        /// </summary>
        void setMaxMoney(bool isFirst = false)
        {
            //竞价按钮最高价
            this.Dispatcher.Invoke(new Action(() =>
            {
                string money = "";

                if (isFirst)
                {
                    money = App.maxMoney.ToString("#,###");
                }
                else
                {
                    ////延时拍卖
                    //if (App.auctionType == "AUCTION_TYPE02")
                    //{
                    //    eventTime = DateTime.Now.AddSeconds(App.auctionTime);
                    //}
                    money = App.maxMoney.ToString("#,###");
                }

                currentMoney.Children.Clear();
                for (int i = 0; i < money.Length; i++)
                {
                    var img = new Image { };
                    img.SetResourceReference(Image.StyleProperty, "money_" + money[i].ToString());
                    currentMoney.Children.Add(img);
                }
                var imga = new Image { };
                imga.SetResourceReference(Image.StyleProperty, "money_y");
                currentMoney.Children.Add(imga);

                Label lblBidPrice = (Label)btnBid.Template.FindName("lblBidPrice", btnBid);
                if (lblBidPrice != null)
                {
                    lblBidPrice.Content = "竞拍出价：" + (App.maxMoney+App.incrementMoney).ToString("#,###") + "元";
                }
            }));
        }

        /// <summary>
        /// 更新竞价记录
        /// </summary>
        void setBidPrice(string Status)
        {
            try
            {
                bidPriceDT.Rows[bidCount - 1]["Status"] = Status;
                DataView bidPriceDV = new DataView(bidPriceDT);
                bidPriceDV.Sort = "bidIndex desc";
                this.Dispatcher.Invoke(new Action(() => { userLV.DataContext = bidPriceDV.ToTable(); }));
            }
            catch (Exception ex)
            {
                Log4C.WriteErrLog("更新出价页面结果,出错记录", ex);
            }
        }

        /// <summary>
        /// 标的确认底价事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void confirmTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan span = eventTime - DateTime.Now;

            if (span.TotalMilliseconds > 0)
            {
                string time = new TimeSpan(0, 0, Convert.ToInt32(span.TotalSeconds)).ToString();
                areaConfirmClock.Children.Clear();
                for (int i = 0; i < time.Length; i++)
                {
                    var img = new Image { Height = 40, Width = 40 };
                    img.SetResourceReference(Image.StyleProperty, "num_" + time[i].ToString());
                    areaConfirmClock.Children.Add(img);
                }
            }
            else
            {
                confirmTimer.Stop();

                btnBid.IsEnabled = true;
                btnConfirmPrice.IsEnabled = false;

                //启动结束定时器
                eventTime = DateTime.Now.AddSeconds(App.auctionTime);
                endTargetTimer.Start();

                //显示控件
                boxConfirmTarget.Visibility = Visibility.Collapsed;
                boxEndTarget.Visibility = Visibility.Visible;
                areaEnd.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 标的开始倒计时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void startTargetTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan span = eventTime - DateTime.Now;
            if (span.TotalMilliseconds > 0)
            {
                string time = new TimeSpan(0, 0, Convert.ToInt32(span.TotalSeconds)).ToString();
                areaStartClock.Children.Clear();
                for (int i = 0; i < time.Length; i++)
                {
                    var img = new Image { };
                    img.SetResourceReference(Image.StyleProperty, "num_" + time[i].ToString());
                    areaStartClock.Children.Add(img);
                }
            }
            else
            {
                startTargetTimer.Stop();
                //启动结束定时器
                eventTime = DateTime.Now.AddSeconds(App.confirmPriceTime);
                confirmTimer.Start();

                //显示控件
                boxStartTarget.Visibility = Visibility.Collapsed;
                boxConfirmTarget.Visibility = Visibility.Visible;
            }
        }

        /// <summary>
        /// 标的结束倒计时事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void endTargetTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan span = eventTime - DateTime.Now;
            if (span.TotalMilliseconds > 0)
            {
                string time = new TimeSpan(0, 0, Convert.ToInt32(span.TotalSeconds)).ToString();
                areaEndClock.Children.Clear();
                for (int i = 0; i < time.Length; i++)
                {
                    var img = new Image { Height = 40, Width = 40 };
                    img.SetResourceReference(Image.StyleProperty, "num_" + time[i].ToString());
                    areaEndClock.Children.Add(img);
                }
            }
            else
            {

                if (App.auctionType == "AUCTION_TYPE02")
                {
                    if (App.canCycle == true)
                    {
                        eventTime = DateTime.Now.AddSeconds(App.auctionTime);
                        App.canCycle = false;
                        btnBid.IsEnabled = true;
                    }
                    else
                    {
                        endTargetTimer.Stop();
                        string time = "00:00:00";
                        areaEndClock.Children.Clear();
                        for (int i = 0; i < time.Length; i++)
                        {
                            var img = new Image { Height = 40, Width = 40 };
                            img.SetResourceReference(Image.StyleProperty, "num_" + time[i].ToString());
                            areaEndClock.Children.Add(img);
                        }
                        btnBid.IsEnabled = false;
                    }
                }
                else
                {
                    endTargetTimer.Stop();
                    string time = "00:00:00";
                    areaEndClock.Children.Clear();
                    for (int i = 0; i < time.Length; i++)
                    {
                        var img = new Image { Height = 40, Width = 40 };
                        img.SetResourceReference(Image.StyleProperty, "num_" + time[i].ToString());
                        areaEndClock.Children.Add(img);
                    }
                    btnBid.IsEnabled = false;
                }
            }
        }

        /// <summary>
        /// 竞价按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBid_Click(object sender, RoutedEventArgs e)
        {
            string currentMoney = (App.incrementMoney + App.maxMoney).ToString();

            if (MessageBox.Show(string.Format("当前竞价：{0}\n确实要竞价吗?", currentMoney), "确认竞价", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                App.sendData(App.cmdType.c04, currentMoney);
                //更新本地竞价记录
                userLVown(currentMoney);
                //开启新线程监听结果
                Thread myThread = new Thread(new ThreadStart(setBidResault));
                myThread.Start();
            }

            btnBid.IsEnabled = false;

        }

        /// <summary>
        /// 设置竞价
        /// </summary>
        private void setBidResault()
        {
            int dtnonow = bidCount - 1;
            Thread.Sleep(App.timespan);
            if (bidPriceDT.Rows[dtnonow]["Status"].ToString() == "等待回复")
            {
                bidPriceDT.Rows[dtnonow]["Status"] = "失败：服务器未响应";
                try
                {
                    DataView dv = new DataView(bidPriceDT);
                    dv.Sort = "bidIndex desc";
                    userLV.Dispatcher.Invoke(new Action(() =>
                    {
                        userLV.DataContext = dv.ToTable();
                        userLV.SetBinding(ListView.ItemsSourceProperty, new Binding());
                    }));
                }
                catch (Exception ex)
                {
                    Log4C.WriteErrLog("响应这次竞价结果,错误信息:", ex);
                }
            }
            //返回线程
            Thread.CurrentThread.Abort();
        }

        /// <summary>
        /// 本地竞价记录
        /// </summary>
        /// <param name="maxMoney"></param>
        private void userLVown(string maxMoney)
        {
            bidCount++;
            bidPriceDT.Rows.Add(bidCount, DateTime.Now.ToString("HH:mm:ss fff"), maxMoney, "等待回复");
            DataView dv = new DataView(bidPriceDT);
            dv.Sort = "bidIndex desc";
            userLV.Dispatcher.Invoke(new Action(() =>
            {
                userLV.DataContext = dv.ToTable();
                userLV.SetBinding(ListView.ItemsSourceProperty, new Binding());
            }));
        }

        /// <summary>
        /// 竞价金额初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BidPrice_Init(object sender, RoutedEventArgs e)
        {
            Label lblBidPrice = (Label)btnBid.Template.FindName("lblBidPrice", btnBid);
            if (lblBidPrice != null)
            {
                lblBidPrice.Content = "竞拍出价：" + (App.maxMoney + App.incrementMoney).ToString("#,###") + "元";
            }
        }

        /// <summary>
        /// 自动重启程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBacklogin_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();

            Process myNewProcess = new Process();
            myNewProcess.StartInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
            myNewProcess.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            myNewProcess.Start();
        }

        /// <summary>
        /// 最小化应用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMinApp_Click(object sender, RoutedEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 关闭应用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCloseApp_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        /// <summary>
        /// 窗体拖动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left) this.DragMove();
        }

        /// <summary>
        /// 链接断开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void DisConnected(object sender, NetEventArgs e)
        {
            MessageBox.Show("服务器连接断开！");
        }

        /// <summary>
        /// 接收数据方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void RecvData(object sender, NetEventArgs e)
        {
            //去除结尾标记
            string reciveData = e.Client.Datagram.Substring(0, e.Client.Datagram.Length - 2);
            //获取请求内容
            string Data = reciveData.Substring(3, reciveData.Length - 3);
            //命令类型
            App.cmdType cmd_type = (App.cmdType)Enum.Parse(typeof(App.cmdType), reciveData.Substring(0, 3).ToString(), true);

            //登录失败
            if (cmd_type == App.cmdType.c02)
            {
                MessageBox.Show(Data);
            }
            //登录成功
            else if (cmd_type == App.cmdType.c03)
            {
                App.islogin = true;
                App.targetStr = Data;
            }
            //更新最高价
            else if (cmd_type == App.cmdType.c05)
            {
                var Resualt = Data.Split('|');

                App.maxMoney = double.Parse(Resualt[1]);
                setMaxMoney();
                if (App.BidUser == Resualt[0].ToString())
                {
                    setBidPrice("竞价成功");
                }

                if (App.auctionType == "AUCTION_TYPE02")
                {
                    App.canCycle=true;
                }
            }
            //竞价失败
            else if (cmd_type == App.cmdType.c06)
            {
                setBidPrice("竞价失败");
            }
            //无效指令
            else
            {
                //
            }
        }

        /// <summary>
        /// 确认标底
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConfirmPrice_Click(object sender, RoutedEventArgs e)
        {
            btnConfirmPrice.IsEnabled = false;

            App.sendData(App.cmdType.c07, "_");

            bidPriceDT.Rows.Add(++bidCount, DateTime.Now.ToString("HH:mm:ss fff"), "", "确认底价");
            DataView dv = new DataView(bidPriceDT);
            userLV.Dispatcher.Invoke(new Action(() =>
            {
                userLV.DataContext = dv.ToTable();
                userLV.SetBinding(ListView.ItemsSourceProperty, new Binding());
            }));
        }
    }
}
